<template>
  <div class="region-list-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>区域管理</span>
          <div class="header-actions">
            <el-button 
              v-if="isSuperAdmin" 
              type="primary" 
              @click="handleAdd"
            >
              <el-icon><Plus /></el-icon>
              新增区域
            </el-button>
            <el-button @click="refreshData" :loading="loading">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="区域名称">
          <el-input
            v-model="searchForm.regionName"
            placeholder="请输入区域名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="区域编码">
          <el-input
            v-model="searchForm.regionCode"
            placeholder="请输入区域编码"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="区域类型">
          <el-select v-model="searchForm.regionType" placeholder="请选择区域类型" clearable style="width: 150px">
            <el-option label="省" :value="1" />
            <el-option label="市" :value="2" />
            <el-option label="区县" :value="3" />
            <el-option label="街道" :value="4" />
            <el-option label="社区" :value="5" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 150px">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 区域树形表格 -->
      <el-table
        v-loading="loading"
        :data="filteredTreeData"
        style="width: 100%"
        border
        row-key="id"
        lazy
        :load="loadNode"
        :tree-props="{ hasChildren: 'hasChildren' }"
        :default-expand-all="false"
        :row-class-name="getRowClassName"
        @expand-change="handleExpandChange"
      >
        <el-table-column prop="regionName" label="区域名称" min-width="200">
          <template #default="{ row, $index }">
            <span class="region-name" :class="getRegionLevelClass(row)">
              <el-icon class="region-icon">
                <Location v-if="row.regionType === 1" />
                <OfficeBuilding v-else-if="row.regionType === 2" />
                <Position v-else-if="row.regionType === 3" />
                <MapLocation v-else-if="row.regionType === 4" />
                <Location v-else />
              </el-icon>
              {{ row.regionName }}
              <el-tag v-if="row.isRoot" :type="getTagType('success')" size="small" style="margin-left: 8px;">根节点</el-tag>
              <el-tag v-else-if="row.isLeaf" :type="getTagType('info')" size="small" style="margin-left: 8px;">叶子节点</el-tag>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="regionCode" label="区域编码" min-width="120" />
        <el-table-column prop="regionType" label="区域类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getTagType(getRegionTypeTagType(row.regionType))">
              {{ getRegionTypeText(row.regionType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="regionLevel" label="区域级别" width="100">
          <template #default="{ row }">
            <el-tag :type="getTagType(getLevelTagType(row.regionLevel))">
              {{ getLevelText(row.regionLevel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getTagType(row.status === 1 ? 'success' : 'danger')">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="communityCount" label="社区数量" width="100">
          <template #default="{ row }">
            <el-tag :type="getTagType('info')" v-if="row.communityCount > 0">{{ row.communityCount }}</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="buildingCount" label="楼栋数量" width="100">
          <template #default="{ row }">
            <el-tag :type="getTagType('warning')" v-if="row.buildingCount > 0">{{ row.buildingCount }}</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="householdCount" label="房户数量" width="100">
          <template #default="{ row }">
            <el-tag :type="getTagType('primary')" v-if="row.householdCount > 0">{{ row.householdCount }}</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="residentCount" label="居民数量" width="100">
          <template #default="{ row }">
            <el-tag :type="getTagType('success')" v-if="row.residentCount > 0">{{ row.residentCount }}</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="occupancyRate" label="入住率" width="100">
          <template #default="{ row }">
            <el-progress 
              v-if="row.occupancyRate && row.occupancyRate > 0" 
              :percentage="row.occupancyRate" 
              :stroke-width="8"
              :show-text="false"
            />
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 树形控制按钮 -->
      <div class="tree-controls" style="margin-top: 10px;">
        <el-button size="small" @click="expandAll">
          <el-icon><Expand /></el-icon>
          展开全部
        </el-button>
        <el-button size="small" @click="collapseAll">
          <el-icon><Fold /></el-icon>
          折叠全部
        </el-button>
        <el-button size="small" @click="expandFirstLevel">
          <el-icon><ArrowDown /></el-icon>
          展开一级
        </el-button>
      </div>

      <!-- 统计信息 -->
      <div class="statistics-container">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card">
              <div class="stat-item">
                <div class="stat-number">{{ totalRegions }}</div>
                <div class="stat-label">总区域数</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card">
              <div class="stat-item">
                <div class="stat-number">{{ totalCommunities }}</div>
                <div class="stat-label">总社区数</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card">
              <div class="stat-item">
                <div class="stat-number">{{ totalBuildings }}</div>
                <div class="stat-label">总楼栋数</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card">
              <div class="stat-item">
                <div class="stat-number">{{ totalResidents }}</div>
                <div class="stat-label">总居民数</div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Location, OfficeBuilding, Position, MapLocation, Expand, Fold, ArrowDown } from '@element-plus/icons-vue'
import { hasMenuPermission } from '@/utils/permission'
import { regionApi, type RegionData } from '@/api/region'
import { getTagType } from '@/utils/message'
import { useUserStore } from '@/store/user'

// 用户状态
const userStore = useUserStore()

// 权限检查
const hasAddPermission = hasMenuPermission('region:create').hasPermission
const hasEditPermission = hasMenuPermission('region:update').hasPermission
const hasDeletePermission = hasMenuPermission('region:delete').hasPermission

// 超级管理员权限检查
const isSuperAdmin = computed(() => userStore.isSuperAdmin)

// 响应式数据
const loading = ref(false)
const treeData = ref<RegionData[]>([])
const expandedKeys = ref<number[]>([]) // 控制展开/折叠的行

// 搜索表单
const searchForm = reactive({
  regionName: '',
  regionCode: '',
  regionType: undefined as number | undefined,
  status: undefined as number | undefined
})

// 计算属性：过滤后的树形数据
const filteredTreeData = computed(() => {
  if (!treeData.value || treeData.value.length === 0) {
    return []
  }

  const filterNode = (nodes: RegionData[]): RegionData[] => {
    return nodes.filter(node => {
      // 检查当前节点是否匹配搜索条件
      const nameMatch = !searchForm.regionName || 
        node.regionName.toLowerCase().includes(searchForm.regionName.toLowerCase())
      const codeMatch = !searchForm.regionCode || 
        node.regionCode.includes(searchForm.regionCode)
      const typeMatch = !searchForm.regionType || 
        node.regionType === searchForm.regionType
      const statusMatch = searchForm.status === undefined || 
        node.status === searchForm.status

      // 递归过滤子节点
      if (node.children && node.children.length > 0) {
        node.children = filterNode(node.children)
      }

      return nameMatch && codeMatch && typeMatch && statusMatch
    })
  }

  return filterNode([...treeData.value])
})

// 计算属性：统计信息
const totalRegions = computed(() => {
  const countNodes = (nodes: RegionData[]): number => {
    return nodes.reduce((count, node) => {
      return count + 1 + (node.children ? countNodes(node.children) : 0)
    }, 0)
  }
  return countNodes(treeData.value)
})

const totalCommunities = computed(() => {
  const sumNodes = (nodes: RegionData[]): number => {
    return nodes.reduce((sum, node) => {
      return sum + (node.communityCount || 0) + (node.children ? sumNodes(node.children) : 0)
    }, 0)
  }
  return sumNodes(treeData.value)
})

const totalBuildings = computed(() => {
  const sumNodes = (nodes: RegionData[]): number => {
    return nodes.reduce((sum, node) => {
      return sum + (node.buildingCount || 0) + (node.children ? sumNodes(node.children) : 0)
    }, 0)
  }
  return sumNodes(treeData.value)
})

const totalResidents = computed(() => {
  const sumNodes = (nodes: RegionData[]): number => {
    return nodes.reduce((sum, node) => {
      return sum + (node.residentCount || 0) + (node.children ? sumNodes(node.children) : 0)
    }, 0)
  }
  return sumNodes(treeData.value)
})

// 获取区域类型文本
const getRegionTypeText = (regionType: number) => {
  const typeMap: Record<number, string> = {
    1: '省',
    2: '市',
    3: '区县',
    4: '街道',
    5: '社区'
  }
  return typeMap[regionType] || '未知'
}

// 获取区域类型标签类型
const getRegionTypeTagType = (regionType: number) => {
  const typeMap: Record<number, string> = {
    1: 'danger',
    2: 'warning',
    3: 'primary',
    4: 'success',
    5: 'info'
  }
  return typeMap[regionType] || 'info'
}

// 获取区域级别文本
const getLevelText = (level: number) => {
  const levelMap: Record<number, string> = {
    1: '省级',
    2: '市级',
    3: '区县',
    4: '街道',
    5: '社区'
  }
  return levelMap[level] || '未知'
}

// 获取区域级别标签类型
const getLevelTagType = (level: number) => {
  const typeMap: Record<number, string> = {
    1: 'danger',
    2: 'warning',
    3: 'primary',
    4: 'success',
    5: 'info'
  }
  return typeMap[level] || 'info'
}

// 加载顶级区域数据
const loadRootRegions = async () => {
  try {
    loading.value = true
    
    // 调用区域树接口获取顶级区域数据
    const response = await regionApi.getRegionTree()
    
    if (response.code === 200 && response.data) {
      treeData.value = response.data
      console.log('顶级区域数据加载成功，数量:', treeData.value.length)
      ElMessage.success({ message: '顶级区域数据加载成功' })
    } else {
      ElMessage.error({ message: response.message || '获取顶级区域失败' })
      treeData.value = []
    }
  } catch (error) {
    console.error('获取顶级区域失败:', error)
    ElMessage.error({ message: '获取顶级区域失败' })
    treeData.value = []
  } finally {
    loading.value = false
  }
}

// 动态加载子节点
const loadNode = async (row: RegionData, treeNode: any, resolve: (data: RegionData[]) => void) => {
  try {
    console.log('开始加载子节点:', row.id, row.regionName)
    
    // 调用接口获取子区域
    const response = await regionApi.getRegionTree(row.id)
    
    if (response.code === 200 && response.data) {
      const children = response.data
      console.log('子节点加载成功:', row.id, '子节点数量:', children.length)
      resolve(children)
    } else {
      console.error('获取子区域失败:', response.message)
      ElMessage.error({ message: response.message || '获取子区域失败' })
      resolve([])
    }
  } catch (error) {
    console.error('获取子区域失败:', error)
    ElMessage.error({ message: '获取子区域失败' })
    resolve([])
  }
}

// 刷新数据
const refreshData = () => {
  loadRootRegions()
}

// 搜索
const handleSearch = () => {
  // 搜索功能通过计算属性实现，无需重新加载数据
  ElMessage.success({ message: '搜索完成' })
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    regionName: '',
    regionCode: '',
    regionType: undefined,
    status: undefined
  })
  ElMessage.success({ message: '搜索条件已重置' })
}

// 新增
const handleAdd = () => {
  ElMessage.info({ message: '新增区域功能待实现' })
}

// 编辑
const handleEdit = (row: RegionData) => {
  ElMessage.info({ message: `编辑区域: ${row.regionName}` })
}

// 删除
const handleDelete = async (row: RegionData) => {
  try {
    await ElMessageBox.confirm(`确定要删除区域"${row.regionName}"吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 调用删除API
    const response = await regionApi.deleteRegion(row.id)
    
    if (response.code === 200) {
      ElMessage.success({ message: '删除成功' })
      // 重新加载数据
      await refreshData()
    } else {
      ElMessage.error({ message: response.message || '删除失败' })
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除区域失败:', error)
      ElMessage.error({ message: '删除失败' })
    }
  }
}

// 展开/折叠行
const handleExpandChange = (expandedKeys: number[]) => {
  expandedKeys.value = expandedKeys
}

// 展开所有行
const expandAll = () => {
  // 由于是按需加载，展开所有需要先加载所有数据
  ElMessage.info({ message: '按需加载模式下，请逐级展开查看子区域' })
}

// 折叠所有行
const collapseAll = () => {
  expandedKeys.value = []
}

// 展开一级节点
const expandFirstLevel = () => {
  expandedKeys.value = treeData.value.filter(node => node.regionLevel === 1).map(node => node.id)
}

// 获取区域层级样式类
const getRegionLevelClass = (row: RegionData) => {
  // 根据区域级别返回不同的样式类
  const level = row.regionLevel || 1
  return `region-level-${level}`
}

// 获取表格行样式类名
const getRowClassName = ({ row }: { row: RegionData }) => {
  // 根据区域级别返回不同的行样式类
  const level = row.regionLevel || 1
  return `table-row-level-${level}`
}

// 组件挂载时加载数据
onMounted(async () => {
  await loadRootRegions()
})
</script>

<style scoped>
.region-list-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-form {
  margin-bottom: 20px;
}

.region-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.region-icon {
  color: #409eff;
}

.tree-controls {
  margin-bottom: 20px;
  text-align: right;
}

.statistics-container {
  margin-top: 20px;
}

.stat-card {
  text-align: center;
}

.stat-item {
  padding: 10px;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

:deep(.el-table__expand-icon) {
  margin-right: 8px;
}

:deep(.el-table__expand-icon .el-icon) {
  font-size: 12px;
}

/* 区域层级颜色样式 */
.region-level-1 {
  color: #303133;
  font-weight: 600;
}

.region-level-2 {
  color: #606266;
  font-weight: 500;
}

.region-level-3 {
  color: #909399;
  font-weight: 400;
}

.region-level-4 {
  color: #c0c4cc;
  font-weight: 400;
}

.region-level-5 {
  color: #dcdfe6;
  font-weight: 400;
}

/* 更深层级的样式 */
.region-level-6,
.region-level-7,
.region-level-8,
.region-level-9,
.region-level-10 {
  color: #e4e7ed;
  font-weight: 400;
}

/* 区域图标颜色跟随层级 */
.region-level-1 .region-icon {
  color: #409eff;
}

.region-level-2 .region-icon {
  color: #67c23a;
}

.region-level-3 .region-icon {
  color: #e6a23c;
}

.region-level-4 .region-icon {
  color: #f56c6c;
}

.region-level-5 .region-icon {
  color: #909399;
}

.region-level-6 .region-icon,
.region-level-7 .region-icon,
.region-level-8 .region-icon,
.region-level-9 .region-icon,
.region-level-10 .region-icon {
  color: #c0c4cc;
}

/* 表格行背景色样式 */
:deep(.table-row-level-1) {
  background-color: #ffffff;
}

:deep(.table-row-level-2) {
  background-color: #f8f9fa;
}

:deep(.table-row-level-3) {
  background-color: #f1f3f4;
}

:deep(.table-row-level-4) {
  background-color: #e8eaed;
}

:deep(.table-row-level-5) {
  background-color: #dadce0;
}

:deep(.table-row-level-6) {
  background-color: #c8c9cc;
}

:deep(.table-row-level-7) {
  background-color: #b8b9bc;
}

:deep(.table-row-level-8) {
  background-color: #a8a9ac;
}

:deep(.table-row-level-9) {
  background-color: #98999c;
}

:deep(.table-row-level-10) {
  background-color: #88898c;
}

/* 鼠标悬停效果 */
:deep(.table-row-level-1:hover) {
  background-color: #f0f2f5 !important;
}

:deep(.table-row-level-2:hover) {
  background-color: #e8eaed !important;
}

:deep(.table-row-level-3:hover) {
  background-color: #dadce0 !important;
}

:deep(.table-row-level-4:hover) {
  background-color: #c8c9cc !important;
}

:deep(.table-row-level-5:hover) {
  background-color: #b8b9bc !important;
}

:deep(.table-row-level-6:hover) {
  background-color: #a8a9ac !important;
}

:deep(.table-row-level-7:hover) {
  background-color: #98999c !important;
}

:deep(.table-row-level-8:hover) {
  background-color: #88898c !important;
}

:deep(.table-row-level-9:hover) {
  background-color: #78797c !important;
}

:deep(.table-row-level-10:hover) {
  background-color: #68696c !important;
}
</style> 